package com.wfw.feichat.controller;

import com.google.common.collect.Lists;
import com.wfw.feichat.bo.UserBo;
import com.wfw.feichat.common.ResponseCode;
import com.wfw.feichat.common.ServerResponse;
import com.wfw.feichat.entity.Friend;
import com.wfw.feichat.entity.User;
import com.wfw.feichat.service.FriendRequestService;
import com.wfw.feichat.service.FriendService;
import com.wfw.feichat.service.UserService;
import com.wfw.feichat.utils.FileUtils;
import com.wfw.feichat.utils.MD5Utils;
import com.wfw.feichat.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @author: wfw
 * @date: 2019-05-21 16:29
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private FriendService friendService;

    @Autowired
    private FriendRequestService friendRequestService;

    /**
     * 登陆（未注册会先注册）
     *
     * @param user
     * @return
     */
    @PostMapping("/registOrLogin")
    public ServerResponse registOrLogin(@RequestBody User user) {

        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
            return ServerResponse.buildErrorMsg("用户名或密码不能为空");
        }

        User userResult = null;

        try {
            user.setPassword(MD5Utils.getMD5Str(user.getPassword()));
        } catch (NoSuchAlgorithmException e) {
            log.error("MD5加密出错", e);
            return ServerResponse.buildErrorRC(ResponseCode.INNER_ERROR);
        }

        if (userService.isUsernameExist(user.getUsername())) {
            //登陆
            userResult = userService.getUserByLogin(user.getUsername(), user.getPassword());
            if (userResult == null) {
                return ServerResponse.buildErrorMsg("用户名或密码错误");
            }
        } else {
            //注册
            userResult = userService.saveUser(user);
        }

        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(userResult, userVo);

        return ServerResponse.buildOk(userVo);
    }

    /**
     * 用户上传头像
     *
     * @param userBo
     * @return
     */
    @PostMapping("/uploadImgBase64")
    public ServerResponse uploadImgBase64(@RequestBody UserBo userBo) {

        //获取前端传过来的base64字符串，然后转换为文件对象再上传
        String base64Data = userBo.getImageData();

        if (StringUtils.isBlank(base64Data)) {
            return ServerResponse.buildErrorMsg("请选择图片文件");
        }

        MultipartFile multipartFile = FileUtils.base64ToMultipartFile(base64Data);
        if (multipartFile == null) {
            return ServerResponse.buildErrorRC(ResponseCode.INNER_ERROR);
        }

        String imgUrl = FileUtils.getFilePath(multipartFile);

        log.info("imgUrl:{}", imgUrl);

        User user = new User();
        user.setId(userBo.getUserId());
        user.setImage(imgUrl);
        user.setImageBig(imgUrl);
        user = userService.updateUserInfo(user);

        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);

        return ServerResponse.buildOk(userVo);
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     */
    @PostMapping("/modifyUserIndfo")
    public ServerResponse modifyUserIndfo(@RequestBody User user) {

        if (user == null || StringUtils.isBlank(user.getId())) {
            return ServerResponse.buildErrorRC(ResponseCode.LACK_PARAM);
        }

        User user1 = userService.getUserById(user.getId());
        if (user1 == null) {
            return ServerResponse.buildErrorMsg("用户不存在");
        }

        // 用户名无法修改
        user.setUsername(null);
        // 修改密码
        if (StringUtils.isNotBlank(user.getPassword())) {
            try {
                user.setPassword(MD5Utils.getMD5Str(user.getPassword()));
            } catch (NoSuchAlgorithmException e) {
                log.error("MD5加密出错", e);
                return ServerResponse.buildErrorRC(ResponseCode.INNER_ERROR);
            }
        }
        // 其他的传什么改什么

        user = userService.updateUserInfo(user);

        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);

        return ServerResponse.buildOk(userVo);
    }

    /**
     * 按用户名查询用户
     *
     * @param username
     * @return
     */
    @PostMapping("/search")
    public ServerResponse searchUser(String username) {
        if (StringUtils.isBlank(username)) {
            return ServerResponse.buildErrorRC(ResponseCode.LACK_PARAM);
        }
        User user = userService.getUserByUsername(username);
        if (user == null) {
            return ServerResponse.buildErrorMsg("用户不存在");
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        return ServerResponse.buildOk(userVo);
    }

    /**
     * 通过用户名发送好友请求
     *
     * @param myUserId       当前用户的id
     * @param friendUsername 被添加的用户名
     * @return
     */
    @PostMapping("/addFriendByUsername")
    public ServerResponse addFriendByUsername(String myUserId, String friendUsername) {

        if (StringUtils.isBlank(myUserId) || StringUtils.isBlank(friendUsername)) {
            return ServerResponse.buildErrorRC(ResponseCode.LACK_PARAM);
        }

        User friendUser = userService.getUserByUsername(friendUsername);
        if (friendUser == null) {
            return ServerResponse.buildErrorMsg("用户不存在");
        }
        if (myUserId.equals(friendUser.getId())) {
            return ServerResponse.buildErrorMsg("不能添加自己");
        }
        Friend friend = friendService.getFriendByUidAndFriendUid(myUserId, friendUser.getId());
        if (friend != null) {
            return ServerResponse.buildErrorMsg("你已经添加过该好友");
        }

        Integer addFriendResult = friendRequestService.addFriendRequest(myUserId, friendUser.getId());
        if (addFriendResult <= 0) {
            return ServerResponse.buildErrorMsg("添加失败");
        } else {
            return ServerResponse.buildOk();
        }

    }

    /**
     * 查询好友申请者列表
     *
     * @param userId
     * @return
     */
    @PostMapping("/getFriendRequests")
    public ServerResponse getFriendRequests(String userId) {
        if (StringUtils.isBlank(userId)) {
            return ServerResponse.buildErrorRC(ResponseCode.LACK_PARAM);
        }
        List<String> uidList = friendRequestService.getSendUidByAcceptUid(userId);

        List<UserVo> userVoList = Lists.newArrayList();
        if (uidList != null && uidList.size() > 0) {
            List<UserVo> userVoList1 = userService.getUserVoListByUidList(uidList);
            if (userVoList1 != null || userVoList1.size() > 0) {
                userVoList = userVoList1;
            }
        }

        return ServerResponse.buildOk(userVoList);
    }

    /**
     * 处理好友请求，通过/忽略
     *
     * @param acceptUserId 当前用户的id
     * @param sendUserId   请求者的id
     * @param operType     操作类型，0忽略，1通过
     * @return
     */
    @PostMapping("/operFriendRequest")
    public ServerResponse operFriendRequest(String acceptUserId, String sendUserId, Integer operType) {
        if (StringUtils.isBlank(acceptUserId) || StringUtils.isBlank(sendUserId) || operType == null) {
            return ServerResponse.buildErrorRC(ResponseCode.LACK_PARAM);
        }
        if (0 == operType.intValue()) {
            //忽略请求，删掉一条记录
            friendRequestService.removeFriendRequest(sendUserId, acceptUserId);
        } else if (1 == operType.intValue()) {
            //通过请求，相互添加好友
            userService.passFriendRequest(acceptUserId, sendUserId);
        }
        return ServerResponse.buildOk();
    }

    /**
     * 获取好友列表
     *
     * @param userId
     * @return
     */
    @PostMapping("/myFriends")
    public ServerResponse myFriends(String userId) {
        if (StringUtils.isBlank(userId)) {
            return ServerResponse.buildErrorRC(ResponseCode.LACK_PARAM);
        }
        List<String> friendUidList = friendService.getfriendUidListByUid(userId);
        List<UserVo> userVoList = Lists.newArrayList();
        if (friendUidList != null && friendUidList.size() > 0) {
            List<UserVo> userVoList1 = userService.getUserVoListByUidList(friendUidList);
            if (userVoList1 != null || userVoList1.size() > 0) {
                userVoList = userVoList1;
            }
        }

        return ServerResponse.buildOk(userVoList);
    }

}
